package com.fang.transfer.file.common;

import com.google.gson.Gson;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class NettyHandle {

    /**
     * 通道管理
     */
    @Autowired
    private ChannelManagement channelManagement;

    @Autowired
    private ApplicationContext applicationContext;

    public NettyHandle() {
        channelManagement = new ChannelManagement();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        serverBootstrap.group(bossGroup, workerGroup)
                //轮询空包
                .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) {
                MyChannelInboundHandler myChannelInboundHandler = applicationContext.getBean(MyChannelInboundHandler.class);
                nioSocketChannel.pipeline().addLast(new LineBasedFrameDecoder(20480));
                nioSocketChannel.pipeline().addLast(new StringDecoder());
                nioSocketChannel.pipeline().addLast(new StringEncoder());
                nioSocketChannel.pipeline().addLast(myChannelInboundHandler);
            }
        }).bind(8888);
    }

    public void send(String id, String code, String msg) {
        ChannelHandlerContext context = channelManagement.get(id);
        if (context == null) {
            throw new RuntimeException("通道不存在" + id);
        }
        context.writeAndFlush(code + msg + "\n");
    }

    public void send(String id, String code, Object data) {
        String jsonData = new Gson().toJson(data);
        send(id, code, jsonData);
    }
}
